package com.homedo.odin.solution.service.bizservice.mng;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.core.common.util.ShortUrlHelper;
import com.homedo.odin.solution.contract.mng.UserRequirePriResponseBean;
import com.homedo.odin.solution.contract.pc.InsertMsgReq;
import com.homedo.odin.solution.enumcode.require.UserRequireStatusEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionTypeEnum;
import com.homedo.odin.solution.model.dto.PcAccountInfo;
import com.homedo.odin.solution.model.dto.ShortMessageBean;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.UserRequire;
import com.homedo.odin.solution.model.request.mng.require.UserRequireReplyRequestBean;
import com.homedo.odin.solution.model.request.mng.require.UserRequireRequestBean;
import com.homedo.odin.solution.model.request.pc.require.UserRequireListRequestBean;
import com.homedo.odin.solution.model.request.pc.require.UserRequirePcRequestBean;
import com.homedo.odin.solution.model.response.mng.require.MngUserRequirePageResponseBean;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.UserRequireServiceImpl;
import com.homedo.odin.solution.service.bizservice.personal.MessageBizService;
import com.homedo.odin.solution.service.common.HomedoService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: ZhangLei
 * @date: 2018/4/9
 * @Description:
 */
@Service
public class MngUserRequireService {

    @Autowired
    private UserRequireServiceImpl userRequireService;

    @Autowired
    private SolutionServiceImpl solutionService;

    @Autowired
    private MessageBizService messageBizService;

    @Autowired
    private HomedoService homedoService;

    /**
     * 需求列表
     */
    public MngUserRequirePageResponseBean getUserRequires(UserRequireRequestBean requestBean) {
        Date createStartTime = null;
        Date createEndTime = null;

        if (requestBean.getStartCreateDate() != null) {
            createStartTime = new Date(requestBean.getStartCreateDate());
        }
        if (requestBean.getEndCreateDate() != null) {
            createEndTime = new Date(requestBean.getEndCreateDate());
        }
        PageHelper.startPage(requestBean.getPageNum(), requestBean.getPageSize());

        PageInfo<UserRequire> pageInfo = new PageInfo<>(userRequireService.queryUserRequireListByParam(null, null,
                requestBean.getStatus(), createStartTime, createEndTime));
        List<UserRequire> dbList = pageInfo.getList();
        if (CollectionUtils.isEmpty(dbList)) {
            return null;
        }

        List<UserRequirePriResponseBean> responseList = new ArrayList<>();
        dbList.forEach(userRequire -> {
            UserRequirePriResponseBean userRequireResponse = new UserRequirePriResponseBean();
            BeanUtils.copyProperties(userRequire, userRequireResponse);

            //增加归属人信息
            if (NumberHelper.validatePositive(userRequire.getSolutionId())) {
                Solution solution = solutionService.getSolution(userRequire.getSolutionId());
                if (solution != null && NumberHelper.validatePositive(solution.getUserId())) {
                    if (solution.getSolutionType().intValue() == SolutionTypeEnum.BRAND_SOLUTION.getDbValue()) {
                        userRequireResponse.setType(SolutionTypeEnum.BRAND_SOLUTION.getDbValue());
                    } else {
                        userRequireResponse.setType(SolutionTypeEnum.EXPERT_SOLUTION.getDbValue());
                    }
                    //获取用户名称
                    PcAccountInfo userMessageInfo = homedoService.getUserMessageInfo(solution.getUserId());
                    if (userMessageInfo != null) {
                        userRequireResponse.setBelonger(solution.getUserId());
                        userRequireResponse.setBelongerName(userMessageInfo.getName());
                        userRequireResponse.setBelongerMobile(userMessageInfo.getMobile());
                    }
                } else {
                    userRequireResponse.setType(0);
                }
            } else {
                userRequireResponse.setType(0);
            }
            responseList.add(userRequireResponse);
        });

        return BeanUtils.transfrom(MngUserRequirePageResponseBean.class, pageInfo);
    }

    public UserRequirePriResponseBean getUserRequireDetail(Integer id) {
        UserRequire userRequire = userRequireService.getUserRequire(id);
        if (userRequire == null) {
            throw new BizException(Meta.CODE_451.getCode(), "该用户需求不存在");
        }

        UserRequirePriResponseBean reponseBean = BeanUtils.transfrom(UserRequirePriResponseBean.class, userRequire);
        reponseBean.setType(0);

        if (NumberHelper.validatePositive(userRequire.getSolutionId())) {
            Solution solution = solutionService.getSolution(userRequire.getSolutionId());
            if (solution == null) {
                throw new BizException(Meta.CODE_451.getCode(), "该方案不存在");
            }

            if (solution.getSolutionType().intValue() == SolutionTypeEnum.BRAND_SOLUTION.getDbValue()) {
                reponseBean.setType(SolutionTypeEnum.BRAND_SOLUTION.getDbValue());
            } else {
                reponseBean.setType(SolutionTypeEnum.EXPERT_SOLUTION.getDbValue());
            }
        }
        return reponseBean;
    }

    /**
     * 回复用户需求
     */
    public void replyUserRequire(Integer reqId, UserRequireReplyRequestBean requestBean) {
        UserRequire userRequire = userRequireService.getUserRequire(reqId);
        if (userRequire == null) {
            throw new BizException(Meta.CODE_451.getCode(), "该用户需求不存在");
        }
        BeanUtils.copyProperties(requestBean, userRequire);
        userRequire.setReplyTime(new Date());
        userRequire.setStatus(UserRequireStatusEnum.REPLY.getKey());
        userRequireService.updateUserRequire(userRequire);

        //发送通知
        Solution solution = solutionService.getSolution(userRequire.getSolutionId());
        if (solution != null) {
            Map<String, String> paramMap = Maps.newHashMap();
            paramMap.put("@@userName", userRequire.getUserName());
            paramMap.put("@@bizId", solution.getSolutionId().toString());
            paramMap.put("@@solution", solution.getSolutionName());
            paramMap.put("@@content", userRequire.getReply());

            InsertMsgReq req = new InsertMsgReq();
            req.setFromeUser(0);
            req.setToUser(userRequire.getUserId());
            req.setCode("solution_demondreply");
            req.setContentMap(paramMap);
            messageBizService.insertMessage(req);
        }
        //针对 未登录用户 首页递交的需求做处理 发送短信
        if (userRequire.getUserId() == 0) {
            ShortMessageBean shortMessageBean = new ShortMessageBean();
            String url = "http://msolution.homedo.com/?source=dxfw";
            //正式环境
            String content = "【河姆渡】尊敬的" + userRequire.getContacts() + "，您在方案馆提交的定制需求，回复内容为" + userRequire
                    .getReply() + ",手机上看方案就在方案馆 M 站" + ShortUrlHelper.convertToSINAShortUrl(url);
            shortMessageBean.setPhone(userRequire.getMobile());
            shortMessageBean.setContent(content);
            shortMessageBean.setAccountId(0);
            homedoService.sendShortMessage(shortMessageBean);
        }
    }

    public void addUserRequire(UserRequirePcRequestBean userRequireRequest) {
        if (NumberHelper.validatePositive(userRequireRequest.getSolutionId())) {
            Solution solution = solutionService.getSolution(userRequireRequest.getSolutionId());
            if (solution == null) {
                throw new BizException(new Meta(Meta.CODE_451.getCode(), "该方案不存在"));
            }
        }
        UserRequire userRequire = new UserRequire();
        BeanUtils.copyProperties(userRequireRequest, userRequire);
        userRequire.setStatus(UserRequireStatusEnum.NOT_REPLY.getKey());
        userRequireService.addUserRequire(userRequire);
    }

    /**
     * 我的需求
     */
    public MngUserRequirePageResponseBean getUserRequiresByUser(UserRequireListRequestBean requestBean) {
        PageHelper.startPage(requestBean.getPageNum(), requestBean.getPageSize());
        Date createStartTime = null;
        Date createEndTime = null;
        if (requestBean.getStartCreateDate() != null) {
            createStartTime = new Date(requestBean.getStartCreateDate());
        }
        if (requestBean.getEndCreateDate() != null) {
            createEndTime = new Date(requestBean.getEndCreateDate());
        }

        PageInfo<UserRequire> pageInfo = new PageInfo<>(
                userRequireService.queryUserRequireListByParam(requestBean.getUserId(),
                        requestBean.getDescription(), requestBean.getStatus(), createStartTime, createEndTime));
        List<UserRequire> dbList = pageInfo.getList();
        if (CollectionUtils.isEmpty(dbList)) {
            return null;
        }

        return BeanUtils.transfrom(MngUserRequirePageResponseBean.class, pageInfo);
    }
}
